<?php

class VariantesCartaController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new VariantesCarta;
        if (isset($_POST['VariantesCarta'])) {
            $model->attributes = $_POST['VariantesCarta'];
            if (Yii::app()->user->checkAccess("supervisor")) {
                if ($model->save()) {
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }
        if (Yii::app()->user->checkAccess("supervisor")) {
            $this->render('create', array(
                'model' => $model,
            ));
        } else {
            $this->redirect(array('/../carta/cartaNutricional/contenidos'));
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        if (isset($_POST['VariantesCarta'])) {
            $model->attributes = $_POST['VariantesCarta'];
            if (Yii::app()->user->checkAccess("supervisor")) {
                if ($model->save()) {
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }
        if (Yii::app()->user->checkAccess("supervisor")) {
            $this->render('create', array(
                'model' => $model,
            ));
        } else {
            $this->redirect(array('/../carta/cartaNutricional/contenidos'));
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('VariantesCarta');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new VariantesCarta('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['VariantesCarta']))
            $model->attributes = $_GET['VariantesCarta'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = VariantesCarta::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'variantes-carta-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Obtiene los variantes de comida segun el tiempo de comida
     * @author Mauricio Chamorro <mrchamorro@utn.edu.ec>
     * @param int $tipoVariante id de tiempo de comida
     */
    public function actionCargarVariantesMenu($tipoVariante) {
        if (Yii::app()->getRequest()->getIsAjaxRequest()) {
            $lista = array();
            //busca todos los variantes de comida desde la base de datos
            $variantes = VariantesCarta::model()->findAll();
            $limite = $this->limiteVarianteTipo($tipoVariante);
            $aux = array();
            //busca las coincidencias entre las variantes de comida de la clase 
            //y las que se encuentran en el sistema para luego ordenar y enviar 
            //los datos preprocesados
            foreach ($variantes as $key => $value) {
                foreach ($limite as $lim) {
                    if ($value['oldValues']['representacion'] == $lim) {
                        $aux['id'] = $value['oldValues']['id'];
                        $aux['representacion'] = $value['oldValues']['representacion'];
                        $aux['descripcion'] = $value['oldValues']['descripcion'];
                        array_push($lista, $aux);
                    }
                }
            }
            echo json_encode($lista);
        }
    }

    /**
     * Permite buscar los tipos de variante de comida segun el tiempo de comida
     * @author Mauricio Chamorro <mchamorro@utn.edu.ec>
     * @param int $tipoVariante
     * @return json
     */
    private function limiteVarianteTipo($tipoVariante) {
        switch ($tipoVariante) {
            case 2: { //Desayno
                    return array('a', 'b');
                    break;
                }
            case 3: {//Media MaÃ±ana
                    return array('c');
                    break;
                }
            case 4: {//almuuerzo
                    return array('a.Sopa', 'b.1', 'b.2', 'b.3', 'c');
                    break;
                }
            case 5: {//media tarde
                    return array('a', 'b');
                    break;
                }
        }
    }

    /**
     * Muestra informacion sobre las variantes de menu de un tiempo de comida
     * @author Mauricio Chamorro <mchamorro@utn.edu.ec>
     * @param int $tipoVariante
     * @return json
     */
    public function actionDescripcionLimiteVarianteTipo($tipoVariante) {
        if (Yii::app()->getRequest()->getIsAjaxRequest()) {
            $limite = $this->limiteVarianteTipo($tipoVariante);
            $contexto = array();
            foreach ($limite as $value) {
                $obj = VariantesCarta::model()->findAll(array('condition' => 'representacion= :representacion', 'params' => array(':representacion' => $value)));
                array_push($contexto, '<b>' . $value . ':</b>  ' . $obj[0]['oldValues']['descripcion']);
            }
            echo json_encode($contexto);
        }
    }

}
